import Vue from "vue";
import App from "./App.vue";
import "./main.css";

import store from "./stores/index.js";

import {
  renderWithQiankun,
  qiankunWindow,
} from "vite-plugin-qiankun/dist/helper";

import _ from "lodash";

import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import VueRouter from "vue-router";
import routerData, {
  beforeEach,
  beforeResolve,
  afterEach,
} from "./router/index";

let router = null;
let _$__key = ''
function render(props) {
  const { container } = props;
  Vue.use(ElementUI);
  Vue.use(VueRouter);
  _$__key = container ? props.activeRule : ''
  router = new VueRouter({
    ...routerData(_$__key),
  });
  new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(container ? container.querySelector("#app") : "#app");
  console.log(router);
  
  window.$provideDataFromeParent = (key) => {
    let _$_globalDataFromParent_$_ = window._$_globalDataFromParent_$_ || {}
    if (key) {
      const value = _$_globalDataFromParent_$_
        ? _$_globalDataFromParent_$_[_$__key]?.[key]
        : undefined
      if (value === undefined) {
        throw new Error(`${key} is not exist`)
      }
      return value
    } else {
      return _$_globalDataFromParent_$_[_$__key] ? _$_globalDataFromParent_$_[_$__key] : null
    }
  }
  window.$sendParentMessage = () => {}
  if (container) {
    store.dispatch("globalDataFromParentStore/setInfo", props.globalData);
    // 设置向父级通信的全局事件
    window.$sendParentMessage = (data) => {
      const event = new CustomEvent("childAppEvent", {
        detail: {
          appMsg: props,
          data: data,
        },
      });
      window.dispatchEvent(event);
    };
    props.onGlobalStateChange((state, prev) => {
      store.dispatch("globalDataFromParentStore/setChangeInfo", state);
    });
    store.watch(
      (state) => state.globalDataFromParentStore.changeInfo, // 监听的数据路径
      (newValue, oldValue) => {
        if (!_.isEqual(newValue, oldValue)) {
          props.setGlobalState({ ...newValue });
        }
      }
    );
  }
  // 路由全局守卫 前置
  router.beforeEach((to, from, next) => {
    return beforeEach(to, from, next)
  })
  // 全局解析守卫
  router.beforeResolve((to, from, next) => {
    return beforeResolve(to, from, next)
  })
  // 全局后置钩子
  router.afterEach((to, from, failure) => {
    return afterEach(to, from, failure)
  })
}

const initQianKun = () => {
  renderWithQiankun({
    mount(props) {
      render(props);
    },
    bootstrap() {
      console.log("bootstrap");
    },
    unmount() {
      console.log("unmount");
    },
    update(props) {
      console.log("update", props);
    },
  });
};
if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({});
}

initQianKun();
